<template>
  <view class="snap-container">
    <view class="equi-id" :style="{height:'178rpx'}">
      <view class="tabs-top">
        <view class="tabs">
          <view class="tabs-item" @click="activeTab = index" :class="{'activeTab':activeTab == index}" v-for="(item,index) in tabsList" :key="index">
            {{item}}
          </view>
        </view>
        <view class="id">
          <picker mode="selector" :range="equipmentList" range-key="equipmentCode" @change="handerChangeEqu">
            <text>{{equipmentCode}}</text>
            <uni-icons type="bottom" size="12" style="margin-left: 8rpx;"></uni-icons>
          </picker>
        </view>
      </view>
      <view class="filter" v-show="activeTab == 0">
        <view class="filter-item">
          <picker mode="date" :value="date" @change="bindDateChange">
            <text>监测日期</text>
            <uni-icons type="bottom" size="12" style="margin-left: 8rpx;"></uni-icons>
          </picker>
        </view>
      </view>
    </view>
    <view class="snap-list" v-show="activeTab == 0">
		<view v-if="snapList.length === 0" class="no-data">
			暂无数据
		</view>
		<scroll-view v-else class="equi-box" scroll-y @scrolltolower="loadMore">
			<view class="snap-item" v-for="(item,index) in snapList" :key="index">
			  <checkbox-group @change="toggleItem(item)">
				  <label class="radio" >
					<checkbox :value="item.id" :checked="item.checked" />
				  </label>
			  </checkbox-group>
			  <image :src="item.pictureUrl ? item.pictureUrl : item.url" mode=""></image>
			  <view class="desc">
			    <view class="time">
			      <text>识别虫数: <text style="color:#EF6A0A;font-size: 28rpx;margin-left: 8rpx;">{{item.totalStatistics || 0}}</text></text>
			      <text style="word-wrap: break-word;width:90%">{{formatTimestamp(item.createTime)}}</text>
			    </view>
			    <view class="pos">
			      <text style="color:#00B23B " @click="annotationDetail(item)">虫情标注</text>
			      <uni-icons type="right" size="12" style="margin-left: 8rpx;" color="#00B23B"></uni-icons>
			    </view>
			  </view>
			</view>
		</scroll-view>
	  <view v-if="snapList.length > 0" class="load-more">
	  	<text v-if="!hasMore">没有更多数据了</text>
	  </view>
    </view>
    <view class="snap-btm">
      <view class="opetion opetions" v-show="activeTab == 0">
		  <checkbox-group @change="toggleAll">
			  <label class="radio">
			    <checkbox :value="isAllSelected" :checked="isAllSelected"  /><text>全选</text>
			  </label>
		  </checkbox-group>
        <!-- <view class="export">
          导出图片地址
        </view> -->
        <view class="download" @click="downImages">
          下载原图
        </view>
      </view>
    </view>
    <view class="air-container" v-show="activeTab == 1">
    	<view class="chart-box box" style="height:800rpx">
			<view class="data-title">
				虫情曲线分析
			</view>
    		<uni-datetime-picker  style="width: 80%;" v-model="range" type="daterange" @change="getDataInfo" />
    		<!-- <echarts ref="echarts" :option="myOption" canvasId="echarts"></echarts> -->
			<view style='height:500rpx'>
             <echarts ref="echarts" :option="myOption" canvasId="echarts" ></echarts>
			</view>
			
    	</view>
    	<view class="air-list box">
			<view class="data-title">
				虫情数据分析
			</view>
			<view class="sort-num">
				<view class="sort">
					<text style="color: #929496; margin-right:8rpx;">识别种类：</text>
					<text style="color: #00B23B;">{{dataInfo.typeNumber?dataInfo.typeNumber:'--'}}</text>
				</view>
				<view class="sort">
					<text style="color: #929496; margin-right:8rpx;">识别数量：</text>
					<text style="color: #00B23B;">{{dataInfo.identifyQuantity?dataInfo.identifyQuantity:'--'}}</text>
				</view>
			</view>
			<uni-table border stripe emptyText="暂无更多数据" >
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center">序号</uni-th>
					<uni-th align="center">虫类</uni-th>
					<uni-th align="left">数量</uni-th>
					<uni-th align="left">时间</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item, i) in dataInfo.dataAnalysisList" :key='i'>
					<uni-td>{{i}}</uni-td>
					<uni-td>{{item.label}}</uni-td>
					<uni-td>{{item.quantity}}</uni-td>
					<uni-td>{{item.createTime}}</uni-td>
				</uni-tr>

			</uni-table>
    	</view>
    </view>
  </view>
</template>

<script>
import echarts from '../../components/echarts-uniapp/echarts-uniapp.vue'
import { configPreset, queryPreset, moveToPreset, getChannelSnap,
   cameraOperation,getInsectSentimentFile,downloadById,equipmentPage,
    curveAnalysis,listAllSimple,dataAnalysis
    } from '../../untils/api.js'
import {formatTimestamp} from '../../untils/pubic.js'
import JSZip from 'jszip';
export default {
	components: {
			echarts
		},
  data() {
    return {
      visibleView: true,
      date: '',
      isHd: true,
      popType: '',
      radio: true,
      activeTab: '1',
      tabsList: ['虫情监测', '虫情分析'],
      flvUrl: '',
      flvHdUrl: '',
      equipmentCode: '',
      pointName: '',
      currFlvUrl: '',
      presetList: [],
	  // 抓拍列表
      snapList: [],
	  silderValue:50,
      selectedItems: [], // 选中的项（存储 id）
	  currpreset:'',
	  tableData:[],
	  params :{
		  deviceCode:'',
		  pageNo:1,
		  pageSize:10
	  },
	  hasMore:true,
	  equipmentList:[],
	  dictData:null,
	  range:[],
	  myOption: null,
	  echartObj: null,
	  cameraCode:'',
	  dataInfo:{
		  dataAnalysisList:null
	  }
    }
  },
  computed: {
    // 计算属性：是否全选
    isAllSelected: {
      get() {
        // 当选中项的数量等于列表项的数量时，全选
        return this.selectedItems.length === this.snapList.length;
      },
      set(value) {
		  console.log(value);
        // 根据全选状态更新 selectedItems
        if (value) {
          this.selectedItems = this.snapList.map(item => item.id);
          this.snapList.forEach(item => item.checked = true);
        } else {
          this.selectedItems = [];
          this.snapList.forEach(item => item.checked = false);
        }
      },
    },
  },
  methods: {
	  formatTimestamp,
	  getDataInfo(){
		  let params = {
			cameraCode:this.cameraCode,
			startTime: this.range[0],
			endTime: this.range[1],
			type:''
		  }
		  
          curveAnalysis(params).then((res) => {
			  let allDataArr = [];
			  let allDate = []
              res.data.forEach((item) => {
               let currLineItem = Object.entries(JSON.parse(item.price))
               currLineItem.forEach(([key, value]) => {
                  let name = this.dictData.find(obj => obj.value === key).label;
                  let obj = {
                      name: name,
                      type:'line',
                      value:key,
                      data:[value]
                    };
					if(allDate.indexOf(item.date, 0) < 0){
                      allDate.push(item.date)
					}
				  
                  let index = allDataArr.findIndex(data => data.value === key)
                  if(index > -1){
                   allDataArr[index].data.push(value)
                  
                  }else{
                    allDataArr.push(obj)
                  }
               })
            })
		    this.echartObj = {
				date:allDate,
				data:allDataArr
			}
			this.showEcharts()
			this.getDataAnalysis(params)
			
		  }) 
	  },
	  showEcharts(){
        this.myOption =  {
			 color:['#00B23B', '#F83315',  '#F8ED15', '#59F815', '#15F8F0', '#1555F8', '#A515F8', 
               '#F81592', '#E11638', '#060606', '#00B23C', '#FFFF00', '#047DF9','#D33529',
               '#FF0000','#000000', '#52143c'],
			    
					legend: {
						show:true,
						data:  this.echartObj.data.map((item) => {
							return item.name
						}),
						type: 'scroll',
  						orient: 'horizontal',
						icon: 'rect',
						bottom: 0,
						height: '200px'
					},
					grid: {
					        // 调整图表的位置和大小，top 表示图表顶部与容器顶部的距离
					        top: '15%', 
					        // 其他 grid 属性，如 left、right、bottom、containLabel 等可根据需要设置
					        left: '3%',
					        right: '4%',
					        bottom: '15%',
					        containLabel: true
					      },
					xAxis: {
						show:true,
						type: 'category',
						data: this.echartObj.date,
						
					},
					yAxis: {
						show:true,
						type: 'value',
						axisLabel: {
							showMinLabel: true, // 显示最小值标签
							showMaxLabel: true, // 显示最大值标签
							interval: 'auto' // 自动调整间隔
						}
					},
					series: this.echartObj.data
				};
	  },
	  async getDictDatas(){
         let str = 'insect_species'
		 const res = await listAllSimple()
		 let arr = res.data.filter(item => item.dictType === str)
		 this.dictData = arr
	  },
	  changeDate(){
        console.log(this.range)
	  },
	  getDataAnalysis(obj){
      let params = {
        cameraCode: obj.cameraCode,
        startTime:obj.startTime,
        endTime:obj.endTime
      }
       dataAnalysis(params).then((res) => {
         let {identifyQuantity, typeNumber, dataAnalysisList = []} = res.data;

         dataAnalysisList && dataAnalysisList.length > 0 &&dataAnalysisList.map((item) => {
           item.label = this.dictData.find(obj => obj.value === item.type).label
         })
         this.dataInfo = {identifyQuantity, typeNumber, dataAnalysisList}
		console.log(this.dataInfo)
       })
    },
	  getDateSevenDaysAgo() {
			const today = new Date(); // 获取当前日期
			const sevenDaysAgo = new Date(today); // 复制当前日期
			sevenDaysAgo.setDate(today.getDate() - 7); // 设置为前第七天
			const year = today.getFullYear(); // 获取年份
			const month = String(today.getMonth() + 1).padStart(2, '0'); // 获取月份（补零）
			const day = String(today.getDate()).padStart(2, '0'); // 获取日期（补零）
							
			// 格式化为 YYYY-MM-DD
			const currDate= `${year}-${month}-${day}`;
		
			// 格式化为 YYYY-MM-DD
			const formattedDate = sevenDaysAgo.toISOString().split('T')[0];
			return [formattedDate,currDate];
		},
	  getEquipmentPage() {
		  const params = {
					pageNo: 1,
					pageSize: 10,
					productType: '001'
				}
		  equipmentPage(params).then(res => {
			  this.equipmentList = res.data.list
		  })
	  },
	  handerChangeEqu(val) {
		  this.equipmentCode = this.equipmentList[val.detail.value].equipmentCode
		  this.params.deviceCode = this.equipmentCode 
		  this.hasMore = true
		  this.snapList = []
		  this.getSnapList();
	  },
	  loadMore() {
	  	if (this.hasMore) {
	  		this.getSnapList();
	  	}
	  },
	  annotationDetail(item) {
		  uni.navigateTo({
		  	url:`/subpackage/insect/annotation?attachmentId=${item.id}&url=${item.url}`
		  })
	  },
	  async downImages() {
		  if(!this.selectedItems.length) return uni.showToast({
		  	title:'请选择图片',
			icon:'none'
		  })
		  const ids = this.selectedItems.join()
		  uni.showLoading({
		  	title:'文件加载中'
		  })
		  const res =await downloadById({ids:ids})
		  const filePath = `${wx.env.USER_DATA_PATH}/temp.zip`; // 临时文件路径
		  
			const fs = wx.getFileSystemManager();
			fs.writeFile({
			  filePath,
			  data: res,
			  encoding: 'binary', // 指定编码为 binary
			  success:() =>{
				console.log('文件保存成功', filePath);
				this.unzipAndPreviewImages(filePath); // 解压并预览图片
				uni.hideLoading()
				this.selectedItems = []
				this.isAllSelected = false
			  },
			  fail(err) {
				console.error('文件保存失败', err);
				wx.showToast({
				  title: '文件保存失败',
				  icon: 'none'
				});
				uni.hideLoading()
			  }
			});
		        
	  },
	  unzipAndPreviewImages(filePath) {
	    const fs = wx.getFileSystemManager();
	    fs.readFile({
	      filePath,
	      encoding: 'binary', // 指定编码为 binary
	      success:(res) =>{
	        const zip = new JSZip();
	        zip.loadAsync(res.data).then((contents) => {
	          const imageUrls = []; // 存储图片的临时路径
	  
	          // 遍历 ZIP 文件中的内容
	          Object.keys(contents.files).forEach((filename) => {
	            const file = contents.files[filename];
	            if (!file.dir && this.isImageFile(filename)) { // 忽略文件夹和非图片文件
	              file.async('arraybuffer').then((fileData) => {
	                // 将图片保存为临时文件
	                const imagePath = `${wx.env.USER_DATA_PATH}/${filename}`;
	                fs.writeFile({
	                  filePath: imagePath,
	                  data: fileData,
	                  encoding: 'binary',
	                  success:() =>{
	                    console.log('图片保存成功', imagePath);
	                    imageUrls.push(imagePath);
	  
	                    // 如果所有图片都已保存，预览图片
	                    if (imageUrls.length === Object.keys(contents.files).length) {
	                      this.previewImages(imageUrls);
	                    }
	                  },
	                  fail(err) {
	                    console.error('图片保存失败', err);
	                  }
	                });
	              });
	            }
	          });
	        }).catch(err => {
	          console.error('解压失败', err);
	          wx.showToast({
	            title: '解压失败',
	            icon: 'none'
	          });
	        });
	      },
	      fail(err) {
	        console.error('读取文件失败', err);
	        wx.showToast({
	          title: '读取文件失败',
	          icon: 'none'
	        });
	      }
	    });
	  },
	  // 判断文件是否为图片
	  isImageFile(filename) {
	    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
	    const ext = filename.split('.').pop().toLowerCase();
	    return imageExtensions.includes(ext);
	  },
	  
	  // 预览图片
	  previewImages(imageUrls) {
	    wx.previewImage({
	      urls: imageUrls, // 图片路径列表
	      current: imageUrls[0], // 当前显示的图片
	      success(res) {
	        console.log('图片预览成功', res);
	      },
	      fail(err) {
	        console.error('图片预览失败', err);
	      }
	    });
	  },
	  async getSnapList() {
		  if (!this.hasMore) return;
		  
		  
		  uni.showLoading({
		  	title:'加载中'
		  })
		  
		  try {
		  	const res = await getInsectSentimentFile(this.params)
		  	if (res.code === 200) {
		  		if (res.data.list.length > 0) {
		  			if (this.params.pageNo === 1) {
		  				this.snapList = res.data.list;
		  			} else {
		  				this.snapList = this.snapList.concat(res.data.list);
		  			}
		  			this.params.pageNo += 1;
		  		} else {
		  			this.hasMore = false;
		  		}
		  	}
		  } catch (err) {
		  	console.error('请求失败', err);
		  } finally {
		  	uni.hideLoading();
		  }
	  },
    toggleAll(val) {
		console.log(val);
      this.isAllSelected = !this.isAllSelected;
    },
    toggleItem(item) {
      item.checked = !item.checked;
      if (item.checked) {
        this.selectedItems.push(item.id);
      } else {
        const index = this.selectedItems.indexOf(item.id);
        if (index > -1) {
          this.selectedItems.splice(index, 1);
        }
      }
	  console.log(this.selectedItems,'selectedItems');
    },
    handerChangeSC(val) { 
		console.log(val);
		const item = this.presetList[val.detail.value]
		this.currpreset = item.pointCode
		this.getSnapList()
	},
    bindDateChange(val) {
      console.log(val);
    },
    // 滑块
    sliderChange(val) {
      console.log(val);
	  const type = val.detail.value >= this.silderValue ? 8 : 9
	  this.silderValue = val.detail.value
	  this.cameraOperationFn(type)
    },
    async cameraOperationFn(type) {
      try {
		  uni.showLoading({
		  	title:'加载中'
		  })
      	const res = await cameraOperation({operation:type,equipmentCode:'AK06047PAJ9EC45'})
		if(res.code == 200) {
			uni.hideLoading()
		}
      } catch (error) {
		  console.log(error,'errrr');
      	//TODO handle the exception
		// uni.hideLoading()
      }
	  
    },
    async queryPresetFn(code) {
      const res = await queryPreset({ deviceId: code })
      console.log(res, '收藏点');
	  this.presetList = res.data
    },
    async configPresetBtn() {
      const data = {
        deviceId: this.equipmentCode,
        pointName: this.pointName
      }
      const res = await configPreset(data)
	  if(res.code == 200) {
		  uni.showToast({
		  	title:'操作成功',
			icon:'none'
		  })
	  }
      this.close()
	  this.pointName = ''
    },
    viewPopup() {
      this.popType = 'view'
      this.queryPresetFn()
      this.$refs.popup.open()
    },
    setPopup() {
      this.popType = 'set'
      this.$refs.popup.open()
    },
    close() {
      this.$refs.popup.close()
    }
  },
  onLoad(options) {
	console.log("++++++++++++", options.cameraCode)
	this.range = this.getDateSevenDaysAgo()
	this.getDictDatas()
	this.getEquipmentPage()
    this.equipmentCode = options.equipmentCode
	this.cameraCode =  options.cameraCode
	this.params.deviceCode = this.equipmentCode
	this.getSnapList()
	this.queryPresetFn(options.equipmentCode)
	this.getDataInfo()
  }
}
</script>
<style lang="scss" scoped>
.load-more {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
		font-size: 24rpx;
		color: #999;
	}
	.no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		/* 根据需要调整 */
		font-size: 16px;
		color: #999;
	}
	.air-container {
		.data-title {
			height: 30rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			margin: 32rpx 0;
		}
		height: 100%;
		overflow: hidden;
		background-color: #f4f5f5;
		.chart-box {
			overflow: hidden;
			padding: 0 24rpx;
			box-sizing: border-box;
			margin-top: 18rpx;
			width: 710rpx;
			height: 500rpx;
		}
		.air-list {
			.sort-num {
				margin: 32rpx auto;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 400;
				font-size: 24rpx;
				width: 100%;
				height: 64rpx;
				background: #F5F5F5;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				.sort {
					flex: 1;
					text-align: center;
				}
			}
			padding: 0 24rpx;
			box-sizing: border-box;
			overflow-y: auto;
			width: 710rpx;
			height: 738rpx;
			margin-top: 18rpx;
			font-weight: 400;
			font-size: 30rpx;
			.list-header {
				line-height: 70rpx;
				display: flex;
				align-items: center;
				font-weight: 400;
				font-size: 24rpx;
				color: #929496;
				padding:0 24rpx;
			}
			::v-deep .uni-list-item {
				height: 100rpx;
			}
			.air-index {
				color: #929496;
			}
			.air-time {
				
				color: #181D21;
			}
			.air-tem {
				text-align: center;
				font-weight: 600;
			}
		}
	}
	::v-deep .uni-date-x--border {
		border-radius: 20px;
		overflow: hidden;
	}
	.no-data {
		height: 100%;
		width: 100%;
		display: flex;
		color: #A1A3A5;
		height: 668rpx;
		justify-content: center;
		align-items: center;
	}
	

	.snap-container {
		height: 100%;
		background: #F4F5F5;
		overflow: hidden;

		.equi-id {
			width: 750rpx;
			height: 178rpx;
			overflow: hidden;
			background: #FFFFFF;

			.tabs-top {
				margin: 30rpx 24rpx 30rpx 30rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.video {
					width: 750rpx;
					height: 422rpx;
					background-color: #fff;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.tabs {
				display: flex;
				align-items: center;
				height: 20px;
			}

			.tabs-item {
				width: 60px;
				height: 15px;
				font-weight: 500;
				font-size: 15px;
				color: #535557;
				line-height: 15px;
				margin-right: 16px;
			}

			.activeTab {
				position: relative;
				color: #00B23C;

				&::after {
					position: absolute;
					bottom: -4px;
					left: 0;
					content: '';
					width: 59px;
					height: 2px;
					background: #00B23C;
					border-radius: 2px 2px 2px 2px;
				}
			}

			.id {
				font-weight: 500;
				font-size: 28rpx;
				color: #181D21;
			}

			.filter {
				display: flex;
				font-weight: 400;
				font-size: 26rpx;
				color: #535457;
				margin: 38rpx 0 0 24rpx;

				.filter-item {
					box-sizing: border-box;
					padding: 0 24rpx;
					height: 50rpx;
					background: #F4F5F5;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 24rpx;
				}
			}
		}

		.snap-list {
			margin: 0 24rpx;
			// height: 1052rpx;
			// overflow: hidden;
			// overflow-y: auto;

			.snap-item {
				display: flex;
				align-items: center;
				margin-top: 18rpx;
				width: 710rpx;
				height: 228rpx;
				background: #FFFFFF;
				border-radius: 16rpx;

				.radio {
					margin: 0 24rpx;
				}

				image {
					width: 320rpx;
					height: 180rpx;
				}

				.desc {
					height: 180rpx;
					margin-left: 24rpx;
					font-weight: 400;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.time {
						font-size: 28rpx;
						color: #A1A3A5;
						display: flex;
						flex-direction: column;
					}

					.pos {
						font-size: 28rpx;
						color: #181B21;
					}
				}
			}
		}

		.snap-btm {
			position: fixed;
			bottom: 0;
			width: 750rpx;
			height: 198rpx;
			background: #FFFFFF;
			.opetions {
				justify-content: space-between;
			}
			.opetion {
				margin: 0 24rpx;
				height: 130rpx;
				display: flex;
				align-items: center;

				.radio {
					height: 40rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #000000;
				}

				.export {
					width: 276rpx;
					height: 90rpx;
					background: #FFFFFF;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					border: 1rpx solid #CACCCE;
					margin: 0 20rpx 0 72rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.download {
					display: flex;
					align-items: center;
					color: #fff;
					justify-content: center;
					width: 210rpx;
					height: 90rpx;
					background: #00B23C;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
				}
				.view {
					width: 334rpx;
					height: 90rpx;
					background: #FFFFFF;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					border: 1rpx solid #CACCCE;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 24rpx;
				}
				
				.set {
					width: 334rpx;
					display: flex;
					align-items: center;
					color: #fff;
					justify-content: center;
					height: 90rpx;
					background: #00B23C;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
				}
			}
		}

		.thoroughfare {
			margin-top: 20rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			height: 112rpx;
			display: flex;
			font-weight: 500;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #181B21;

			.thoroughfare-type {
				font-weight: 400;
				color: #181B21;
				display: flex;
				align-items: center;
			}
		}
	}
	.equi-box {
		height: calc(100vh - 400rpx);
		/* 减去顶部高度 */
		overflow-y: auto;
	}
</style>